#!/usr/bin/perl
#
#	Author:  Brandon Shields (brandon.d.shields at gmail dot com)
#	Based on source by: Steve Adeff from ragetvgrab
#		and the guys at The Shepherd (http://svn.whuffy.com)
#
#	Project lives at: http://code.google.com/p/mythvideo-scanner/

use Getopt::Long;

my $version=1.00;

my $help=0;
my $prune=0;

#Process options
GetOptions (
	'help' => \$help,
	'prune' => \$prune,
#	'recurse' => \$recurse,
);

my $video_path= $ARGV[0];

if($help == 1 || length $video_path == 0 )
{
	print "mythvideo-prune\n";
	print "version: $version\n";
	print "\n";
	print "Usage: mythvideo-prune.pl <options> <path>\n";
	print "\n";
	print "Options:\n";
	print "--prune     Recursively deletes directories\n";
	print "            that have less then 1MB of content.\n";
	print "            Omitting this parameter only does a test run";
	print "\n";
	exit 0;
}




$size = process_branch($video_path,0);
printf "$video_path: %.3f GB\n", $size/1024/1024/1024;

sub process_branch
{
	my @files;
	my $path;
	my $level;
	my $skip;	
	my $dir_size=0;
	$path=shift;
	$level=shift;
	if( -d"$path")
	{
		opendir(hDir, $path) || return;
		@files=readdir(hDir);
		closedir(hDir);
	}
	else
	{
		#remove leading slash
		$path =~ s/^\/?//;
		push(@files,$path);
		$path = '';
	}

	foreach $file (@files)
	{
		#ignore . and .. and 'dot files' special folders
		next if $file =~ /^\./;

		#check for directory
		if( -d"$path/$file")
		{
			my $thissize = process_branch("$path/$file", $level + 1);
#			print "$path/$file: $thissize bytes\n";
			if($level == 0)
			{
				my $pretty_size;
				$pretty_size = sprintf("%.3f",$thissize/1024/1024);
				if($thissize < 1000000)
				{
					print "\n\x1b\x5b0;31m$path/$file" . "\x1b\x5b0m\n";
					print "Directory only $pretty_size MB, deleting\n";
					delete_all("$path/$file");
				}
				else{
					print "\n\x1b\x5b0;31m$path/$file" . "\x1b\x5b0m\n";
					print "Directory $pretty_size MB, Won't Delete\n";
				}
			}
			$dir_size = $dir_size + $thissize;
		}
		else
		{
			@stats = stat("$path/$file");
			$dir_size = $dir_size + $stats[7];
		}

	}
	return $dir_size;
}

sub delete_all
{
	my @files;
	my $path;
	my $skip;	
	my $dir_size=0;
	$path=shift;

	if( -d"$path")
	{
		opendir(hDir, $path) || return;
		@files=readdir(hDir);
		closedir(hDir);
	}
	else
	{
		#remove leading slash
		$path =~ s/^\/?//;
		push(@files,$path);
		$path = '';
	}

	foreach $file (@files)
	{
		#ignore . and .. and 'dot files' special folders
		next if $file =~ /^\./;

		#check for directory
		if( -d"$path/$file")
		{
			print "Entering dir:  $path/$file\n";
			delete_all("$path/$file");
			print "Deleting dir:  $path/$file\n";
			if($prune)
			{
				rmdir("$path/$file");
			}
		}
		else
		{
			print "Deleting file: $path/$file\n";
			if($prune)
			{
				unlink("$path/$file");
			}
		}
	}
	print "Deleting dir:  $path\n";
	if($prune)
	{
		rmdir("$path");
	}
}
